package com.immortal.core.converter;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Component
public class LocalDateTimeConverter implements Converter<String, LocalDateTime> {
    private static final List<String> formats = new ArrayList(4);

    public LocalDateTimeConverter() {
    }

    public LocalDateTime convert(String source) {
        String value = source.trim();
        if ("".equals(value)) {
            return null;
        } else if (source.matches("^\\d{4}-\\d{1,2}$")) {
            return this.parseDate(source, (String) formats.get(0));
        } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) {
            return this.parseDate(source, (String) formats.get(1));
        } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")) {
            return this.parseDateTime(source, (String) formats.get(2));
        } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
            return this.parseDateTime(source, (String) formats.get(3));
        } else {
            throw new IllegalArgumentException("Invalid dateSource '" + source + "'");
        }
    }

    public LocalDateTime parseDateTime(String dateStr, String format) {
        LocalDateTime date = null;
        try {
            DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
            date = LocalDateTime.parse(dateStr, df);
        } catch (Exception var5) {
            var5.printStackTrace();
        }
        return date;
    }
    public LocalDateTime parseDate(String dateStr, String format) {
        LocalDateTime date = null;
        try {

            DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
            date =  LocalDateTime.of(LocalDate.parse(dateStr,df), LocalTime.of(0,0,0));
        } catch (Exception var5) {
            var5.printStackTrace();
        }

        return date;
    }

    static {
        formats.add("yyyy-MM");
        formats.add("yyyy-MM-dd");
        formats.add("yyyy-MM-dd hh:mm");
        formats.add("yyyy-MM-dd hh:mm:ss");
    }
}